package com.zheng.study.web.shiro.filter;

import com.zheng.study.base.utils.CommonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.servlet.AdviceFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * session拦截器
 * ============================================================================
 * author : xuzhou
 * createDate:  2015/12/11 11:20
 * ============================================================================
 */
public class SysSessionFilter extends AdviceFilter {

	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		String userName = (String) SecurityUtils.getSubject().getPrincipal();
		if (userName == null) {
			PrintWriter out = response.getWriter();
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append("<script type=\"text/javascript\">");
			stringBuffer.append("window.location.href=\""+ CommonUtil.getServerPath(httpRequest)+"/main/login\"");
			stringBuffer.append("</script>");
			out.print(stringBuffer.toString());
			return false;
		}
		return super.preHandle(request, response);
	}

	@Override
	protected void postHandle(ServletRequest request, ServletResponse response) throws Exception {
		super.postHandle(request, response);
	}

}
